﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Security;
using SaladBar.Service.Services.Users;
using SaladBar.Domain.Users;
using SaladBar.Domain;

namespace SaladBar.Core.Security
{
    public class SaladBarMembershipProvider : MembershipProvider
    {
        private UserService _UserService;

        public SaladBarMembershipProvider(UserService userService)
        {
            this._UserService = userService;
        }

        public override string ApplicationName
        {
            get
            {
                throw new NotImplementedException();
            }
            set
            {
                throw new NotImplementedException();
            }
        }

        public override bool ChangePassword(string username, string oldPassword, string newPassword)
        {
            try
            {
                this._UserService.ChangePassword(username, oldPassword, newPassword);
                return true;
            }
            catch (MembershipPasswordException)
            {
                return false;
            }
        }

        public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer)
        {
            try
            {
                this._UserService.ChangePasswordQuestionAndAnswer(username, password, newPasswordQuestion, newPasswordAnswer);
                return true;
            }
            catch (MembershipPasswordException)
            {
                return false;
            }
        }

        public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status)
        {
            User user = this._UserService.Create(username, password, email, passwordQuestion, passwordAnswer, isApproved, providerUserKey, out status);

            if (status != MembershipCreateStatus.Success)
                return null;

            return this.UserToMembershipUser(user);
        }

        public override bool DeleteUser(string username, bool deleteAllRelatedData)
        {
            this._UserService.DeleteUser(username);
            return true;
        }

        public override bool EnablePasswordReset
        {
            get { return true; }
        }

        public override bool EnablePasswordRetrieval
        {
            get { return false; }
        }

        public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords)
        {
            PagedQueryResult<User> queryResult = this._UserService.FindUsersByEmail(emailToMatch, pageIndex + 1, pageSize);
            totalRecords = queryResult.TotalCount;
            MembershipUserCollection collection = new MembershipUserCollection();
            foreach (User u in queryResult)
                collection.Add(this.UserToMembershipUser(u));
            return collection;
        }

        public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)
        {
            PagedQueryResult<User> queryResult = this._UserService.FindUsersByUsername(usernameToMatch, pageIndex + 1, pageSize);
            totalRecords = queryResult.TotalCount;
            MembershipUserCollection collection = new MembershipUserCollection();
            foreach (User u in queryResult)
                collection.Add(this.UserToMembershipUser(u));
            return collection;
        }

        public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
        {
            PagedQueryResult<User> queryResult = this._UserService.GetAllUsers(pageIndex + 1, pageSize);
            totalRecords = queryResult.TotalCount;
            MembershipUserCollection collection = new MembershipUserCollection();
            foreach (User u in queryResult)
                collection.Add(this.UserToMembershipUser(u));
            return collection;
        }

        public override int GetNumberOfUsersOnline()
        {
            return this._UserService.GetNumberOfUsersOnline(this.UserIsOnlineTimeWindow);
        }

        public override string GetPassword(string username, string answer)
        {
            //not going to implement this - using a one way hashing scheme
            throw new NotSupportedException();
        }

        public override MembershipUser GetUser(string username, bool userIsOnline)
        {
            User user = this._UserService.GetByUsername(username, userIsOnline);
            return this.UserToMembershipUser(user);
        }

        public override MembershipUser GetUser(object providerUserKey, bool userIsOnline)
        {
            User user = this._UserService.GetById((int)providerUserKey, userIsOnline);
            return this.UserToMembershipUser(user);
        }

        public override string GetUserNameByEmail(string email)
        {
            return this._UserService.GetUsernameByEmail(email);
        }

        public override int MaxInvalidPasswordAttempts
        {
            get { throw new NotImplementedException(); }
        }

        public override int MinRequiredNonAlphanumericCharacters
        {
            get { throw new NotImplementedException(); }
        }

        public override int MinRequiredPasswordLength
        {
            get { throw new NotImplementedException(); }
        }

        public override int PasswordAttemptWindow
        {
            get { throw new NotImplementedException(); }
        }

        public override MembershipPasswordFormat PasswordFormat
        {
            get { throw new NotImplementedException(); }
        }

        public override string PasswordStrengthRegularExpression
        {
            get { throw new NotImplementedException(); }
        }

        public override bool RequiresQuestionAndAnswer
        {
            get { throw new NotImplementedException(); }
        }

        public override bool RequiresUniqueEmail
        {
            get { throw new NotImplementedException(); }
        }

        public int UserIsOnlineTimeWindow
        {
            get { throw new NotImplementedException(); }
        }

        public override string ResetPassword(string username, string answer)
        {
            if (!this.EnablePasswordReset)
                throw new NotSupportedException();
            if (this.RequiresQuestionAndAnswer)
            {
                User user = this._UserService.GetByUsername(username, false);
                if (user.PasswordAnswer.ToLower() != answer.ToLower())
                    throw new MembershipPasswordException();
            }
            
            return this._UserService.ResetPassword(username);
        }

        public override bool UnlockUser(string userName)
        {
            this._UserService.UnlockUser(userName);
            return true;
        }

        public override void UpdateUser(MembershipUser user)
        {
            throw new NotImplementedException();
        }

        public override bool ValidateUser(string username, string password)
        {
            throw new NotImplementedException();
        }

        private MembershipUser UserToMembershipUser(User user)
        {
            return new MembershipUser("SaladBarMembershipProvider",
                user.Username,
                user.Id,
                user.Email,
                user.PasswordQuestion,
                user.PasswordAnswer,
                user.IsApproved,
                user.IsLockedOut,
                user.CreateDate,
                user.LastLoginDate.GetValueOrDefault(),
                user.LastActivityDate,
                user.LastPasswordChangeDate.GetValueOrDefault(),
                user.LastLockoutDate.GetValueOrDefault());
        }
    }
}
